package org.jbit.news.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.jbit.news.entity.*;

public class BaseDao {
	private String driver=ConfigManager.getProperty("driver");
	private String url=ConfigManager.getProperty("url");
	private String user=ConfigManager.getProperty("user");
	private String password=ConfigManager.getProperty("password");
	protected Connection conn=null;
	protected PreparedStatement pstmt=null;
	protected ResultSet rs=null;

	public Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void closeAll(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public int exceuteUpdate(String sql,Object...prams){
		int result=0;
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			for(int i=0;i<prams.length;i++){
				pstmt.setObject(i+1, prams[i]);
			}
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public int exceuteUpdate(String sql,int prams){
		int result=0;
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			if(pstmt!=null){
				pstmt.setObject(1,prams);
			}
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public ResultSet exceuteQuery(String sql,String... param){
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			if(pstmt!=null){
				for (int i = 0; i < param.length; i++) {
					pstmt.setObject(i+1, Integer.valueOf(param[i]));
				}
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
	public ResultSet exceuteQuery(String sql,int j,int i){
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, j);
			pstmt.setInt(2, i);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
	public ResultSet exceuteQuery(String sql,int param){
		conn=this.getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			if(pstmt!=null){
				pstmt.setObject(1,param);
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
}
